//
//  EditPhoneViewController.m
//  ChatKit-OC
//
//  Created by th on 2017/3/30.
//  Copyright © 2017年 ElonChan. All rights reserved.
//

#import "EditPhoneViewController.h"
#import "UIAutoScrollView.h"
#import "LCChatKitExample.h"

@interface EditPhoneViewController () <UITextFieldDelegate>

@property (nonatomic, strong) UITextField *phoneTF; //手机号码

@property (nonatomic, strong) UITextField *passwordTF;

@property (nonatomic, strong)  UIButton *getCodeButton;//发送验证码按钮

@property (nonatomic, strong) UITextField *codeTF;//验证码

@property (nonatomic, strong)  NSTimer *timer;

@end

@implementation EditPhoneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"修改手机号码";
    
    [self setupUI];
}

- (void)hideKeyboard {
    [self.view endEditing:YES];
}

- (void)setupUI {
    
    self.view.backgroundColor = [UIColor colorWithRed:0.91 green:0.93 blue:0.93 alpha:1.00];
    
    float y = AUTO_MATE_HEIGHT(0.0f);
    
    UIAutoScrollView *keyScrollView = [[UIAutoScrollView alloc] initWithFrame:CGRectMake(0, y, kMainWidth, kMainHeight - NavigationBar_HEIGHT - STATUS_BAR_HEIGHT)];
    keyScrollView.backgroundColor = [UIColor whiteColor];
    
    [keyScrollView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)]];
    
    [self.view addSubview:keyScrollView];
    
    y += 20;
    
    _phoneTF = [[UITextField alloc]initLeftLabelTypeWithY:y placeholder:@"请输入新的手机号" leftLabelText:@"手机号"];
    _phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    _phoneTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    [_phoneTF addLineViewLeftSpace:kSpaceX rightSpace:kSpaceX positionType:kBottom_Type];
    [keyScrollView addSubview:_phoneTF];
    
    y = _phoneTF.maxY_pro;
    
    _codeTF = [[UITextField alloc]initLeftLabelTypeWithY:y placeholder:nil leftLabelText:@"验证码"];
    _codeTF.keyboardType = UIKeyboardTypeNumberPad;
    [keyScrollView addSubview:_codeTF];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(_codeTF.x_pro, _codeTF.maxY_pro, kMainWidth - _codeTF.x_pro*2, 1)];
    line.backgroundColor = kLineViewColor;
    
    [keyScrollView addSubview:line];
    
    //获取验证码
    _getCodeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_getCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    _getCodeButton.backgroundColor = [UIColor colorWithRed:0.04 green:0.43 blue:0.93 alpha:1.00];
    [_getCodeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _getCodeButton.titleLabel.font = [UIFont systemFontOfSize:15];
    
    float width = AUTO_MATE_WIDTH(100.0f);
    
    float x = kRight(_codeTF)- width - 10.0;
    _getCodeButton.frame = CGRectMake(x, (_phoneTF.height_pro - _phoneTF.height_pro * 0.6) * 0.5 + y, width, _phoneTF.height_pro * 0.6);
    [_getCodeButton addTarget:self action:@selector(getCheckCode) forControlEvents:UIControlEventTouchUpInside];
    [keyScrollView addSubview:_getCodeButton];
    _codeTF.width_pro = _codeTF.width_pro - width - kSpaceX;
    
    
    
    y = _codeTF.maxY_pro;
    
    _passwordTF = [[UITextField alloc]initLeftLabelTypeWithY:y placeholder:@"请当前密码" leftLabelText:@"密码"];
    _passwordTF.delegate = self;
    _passwordTF.returnKeyType = UIReturnKeyDone;
    _passwordTF.secureTextEntry = YES;
    _passwordTF.keyboardType = UIKeyboardTypeDefault;
    _passwordTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    [_passwordTF addLineViewLeftSpace:kSpaceX rightSpace:kSpaceX positionType:kBottom_Type];
    
    [keyScrollView addSubview:_passwordTF];
    
    y = _passwordTF.maxY_pro + 20;
    
    
    UIButton *registerBtn = [[UIButton alloc] initWithFrame:CGRectMake(kSpaceX, y, kMainWidth - kSpaceX*2, 35)];
    
    registerBtn.backgroundColor = [UIColor colorWithRed:0.06 green:0.47 blue:0.91 alpha:1.00];
    
    [registerBtn setTitle:@"确定" forState:UIControlStateNormal];
    
    [registerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [registerBtn addTarget:self action:@selector(checkTap) forControlEvents:UIControlEventTouchUpInside];
    
    [keyScrollView addSubview:registerBtn];
    
    [keyScrollView addAutoScrollAbility];
}
- (void)showMsg:(NSString *)msg type:(LCCKMessageNotificationType)type {
    [LCCKUtil showNotificationWithTitle:msg
                               subtitle:nil
                                   type:type];
}
#pragma mark - 获取验证码按钮响应
- (void)getCheckCode
{
    BOOL isPhone = [RegExpValidate validateMobile:_phoneTF.text];//正则表达式
    if ([_phoneTF.text isEqualToString:@""] || [_phoneTF.text length] == 0) {
        //手机号码不为空
        [self showMsg:@"手机号码不能为空" type:LCCKMessageNotificationTypeError];
        return;
    } else if (isPhone) {
        [self getCodeSuccess];
        
        //改变按钮背景图片
        [_getCodeButton setBackgroundImage:[UIImage imageNamed:@"btn_qrcode"] forState:0];
        return;
    } else {
        [self showMsg:@"手机号码错误" type:LCCKMessageNotificationTypeError];
        _phoneTF.text = nil;
        return;
    }
    
}

// 倒计时
- (void)cutTimeDown:(NSTimer *)timer {
    _getCodeButton.enabled = NO;
    static int time = 60;
    NSString *title = [NSString stringWithFormat:@"剩下（%ds）",time];
    [_getCodeButton setTitle:title forState:UIControlStateDisabled];
    time--;
    if (time == -1) {
        _getCodeButton.enabled = YES;
        [_getCodeButton setTitle:@"重发验证码" forState:0];
        time = 60;
        [timer invalidate];
        timer = nil;
        _timer = nil;
    }
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_timer invalidate];
    _timer = nil;
}

#pragma mark - 请求验证码
- (void)getCodeSuccess
{
    [self.view endEditing:YES];
    
    MJWeakSelf;
    
    [AVOSCloud requestSmsCodeWithPhoneNumber:_phoneTF.text callback:^(BOOL succeeded, NSError *error) {
        // 发送失败可以查看 error 里面提供的信息
        
        if (succeeded) {
            [self showMsg:@"验证码发送成功" type:LCCKMessageNotificationTypeSuccess];
            
            weakSelf.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(cutTimeDown:) userInfo:nil repeats:YES];
            
        } else {
            [self showMsg:[error localizedDescription] type:LCCKMessageNotificationTypeError];
        }
        
    }];
    
}


- (void)checkTap {
    [self hideKeyboard];
    
    BOOL isPhone = [RegExpValidate validateMobile:_phoneTF.text];//正则表达式
    if ([_phoneTF.text isEqualToString:@""] || [_phoneTF.text length] == 0 || !isPhone) {
        //手机号码不为空
        [LCCKUtil showNotificationWithTitle:@"手机号码错误" subtitle:nil type:LCCKMessageNotificationTypeError];
        return;
    } else if (_codeTF.text.length == 0) {
        [LCCKUtil showNotificationWithTitle:@"请输入验证码" subtitle:nil type:LCCKMessageNotificationTypeError];
        return;
    } else if (_passwordTF.text.length == 0) {
        [LCCKUtil showNotificationWithTitle:@"请输入密码" subtitle:nil type:LCCKMessageNotificationTypeError];
        return;
    } else {
        
        AVUser *currentUser = [AVUser currentUser];
        
        MJWeakSelf;
        void(^updatePhone)() = ^() {
            
            [LCCKUtil showProgressText:@"Waiting ..." duration:30.0f];
            
            [AVUser logInWithUsernameInBackground:currentUser.username password:weakSelf.passwordTF.text block:^(AVUser * _Nullable user, NSError * _Nullable error) {
                
                if (error) {
                    [LCCKUtil hideProgress];
                    [weakSelf showMsg:@"密码错误" type:LCCKMessageNotificationTypeError];
                    
                } else {
                    
                    [AVOSCloud verifySmsCode:_codeTF.text mobilePhoneNumber:_phoneTF.text callback:^(BOOL succeeded, NSError * _Nullable error) {
                        
                        if (succeeded) {
                            
                            [LCCKUtil hideProgress];
                            
                            currentUser.mobilePhoneNumber = _phoneTF.text;
                            
                            [currentUser saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                                
                                if (succeeded) {
                                    
                                    if (weakSelf.editPhoneBlock) {
                                        weakSelf.editPhoneBlock(weakSelf.phoneTF.text);
                                        
                                        [weakSelf.navigationController popViewControllerAnimated:YES];
                                        
                                        [weakSelf showMsg:@"更改成功" type:LCCKMessageNotificationTypeSuccess];
                                    }
                                    
                                } else {
                                    [weakSelf showMsg:[error localizedDescription] type:LCCKMessageNotificationTypeError];
                                }
                            }];
                            
                        } else {
                            [LCCKUtil hideProgress];
                            [weakSelf showMsg:[error localizedDescription] type:LCCKMessageNotificationTypeError];
                        }
                        
                    }];
                }
                
            }];
            
        };
        
        void(^queryPhone)() = ^() {
            
            AVQuery *query = [AVQuery queryWithClassName:kUser];
            
            [query whereKey:@"username" equalTo:currentUser.username];
            
            [query findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
                
                if (!error) {
                    
                    if (objects.count > 0) {
                        
                        [LCCKUtil showNotificationWithTitle:@"该号码已注册" subtitle:nil type:LCCKMessageNotificationTypeError];
                        
                        
                    } else {
                        
                        updatePhone();
                        
                    }
                } else {
                    [LCCKUtil showNotificationWithTitle:[error localizedDescription] subtitle:nil type:LCCKMessageNotificationTypeError];
                }
                
                
            }];
            
        };
        
        updatePhone();
        
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
